<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>用户关注管理</span>
      </div>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="queryParams.userId" placeholder="请输入用户ID" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="关注列表" name="following">
          <el-table v-loading="loading" :data="followingList" @selection-change="handleFollowingSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="关注者" align="center">
              <template slot-scope="scope">
                <span>{{ getUserNickName(scope.row.followerId) }} (ID: {{ scope.row.followerId }})</span>
              </template>
            </el-table-column>
            <el-table-column label="被关注者" align="center">
              <template slot-scope="scope">
                <span>{{ getUserNickName(scope.row.followedId) }} (ID: {{ scope.row.followedId }})</span>
              </template>
            </el-table-column>
            <el-table-column label="关注时间" align="center" prop="createTime" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleUnfollow(scope.row)">取消关注</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="followingTotal > 0" :total="followingTotal" :page.sync="followingQueryParams.pageNum" :limit.sync="followingQueryParams.pageSize" @pagination="getFollowingList" />
        </el-tab-pane>
        <el-tab-pane label="粉丝列表" name="followers">
          <el-table v-loading="loading" :data="followersList" @selection-change="handleFollowersSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="关注者" align="center">
              <template slot-scope="scope">
                <span>{{ getUserNickName(scope.row.followerId) }} (ID: {{ scope.row.followerId }})</span>
              </template>
            </el-table-column>
            <el-table-column label="被关注者" align="center">
              <template slot-scope="scope">
                <span>{{ getUserNickName(scope.row.followedId) }} (ID: {{ scope.row.followedId }})</span>
              </template>
            </el-table-column>
            <el-table-column label="关注时间" align="center" prop="createTime" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-view" @click="handleViewUser(scope.row.followerId)">查看用户</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="followersTotal > 0" :total="followersTotal" :page.sync="followersQueryParams.pageNum" :limit.sync="followersQueryParams.pageSize" @pagination="getFollowersList" />
        </el-tab-pane>
      </el-tabs>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleFollow">添加关注</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 添加关注对话框 -->
    <el-dialog :title="followTitle" :visible.sync="followOpen" width="500px" append-to-body>
      <el-form ref="followForm" :model="followForm" :rules="followRules" label-width="100px">
        <el-form-item label="关注者ID" prop="followerId">
          <el-input v-model="followForm.followerId" placeholder="请输入关注者ID" />
        </el-form-item>
        <el-form-item label="被关注者ID" prop="followedId">
          <el-input v-model="followForm.followedId" placeholder="请输入被关注者ID" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFollowForm">确 定</el-button>
        <el-button @click="cancelFollow">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { list, follow, unfollow } from "@/api/system/follows";
import { getUser } from "@/api/system/user";

export default {
  name: "UserFollows",
  data() {
    return {
      // 活动标签页
      activeTab: "following",
      // 遮罩层
      loading: true,
      // 关注列表
      followingList: [],
      // 粉丝列表
      followersList: [],
      // 关注总数
      followingTotal: 0,
      // 粉丝总数
      followersTotal: 0,
      // 关注查询参数
      followingQueryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null
      },
      // 粉丝查询参数
      followersQueryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null
      },
      // 显示搜索条件
      showSearch: true,
      // 查询参数
      queryParams: {
        userId: null
      },
      // 弹出层标题
      followTitle: "",
      // 是否显示弹出层
      followOpen: false,
      // 表单参数
      followForm: {},
      // 表单校验
      followRules: {
        followerId: [{ required: true, message: "关注者ID不能为空", trigger: "blur" }],
        followedId: [{ required: true, message: "被关注者ID不能为空", trigger: "blur" }]
      },
      // 用户信息缓存
      userInfoCache: new Map()
    };
  },
  created() {
    // 检查路由参数中是否有userId
    const userId = this.$route.query.userId;
    if (userId) {
      this.queryParams.userId = userId;
    }
    this.getFollowingList();
  },
  methods: {
    /** 查询关注列表 */
    getFollowingList() {
      this.loading = true;
      // 使用后端分页接口查询关注列表
      const query = {
        ...this.followingQueryParams,
        followerId: this.queryParams.userId
      };
      list(query).then(response => {
        this.followingList = response.rows;
        this.followingTotal = response.total;
        // 获取用户信息
        this.fetchUserInfos(this.followingList);
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    /** 查询粉丝列表 */
    getFollowersList() {
      this.loading = true;
      // 使用后端分页接口查询粉丝列表
      const query = {
        ...this.followersQueryParams,
        followedId: this.queryParams.userId
      };
      list(query).then(response => {
        this.followersList = response.rows;
        this.followersTotal = response.total;
        // 获取用户信息
        this.fetchUserInfos(this.followersList);
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    /** 获取用户信息 */
    async fetchUserInfos(list) {
      for (let item of list) {
        // 获取关注者信息
        if (item.followerId && !this.userInfoCache.has(item.followerId)) {
          try {
            const response = await getUser(item.followerId);
            this.userInfoCache.set(item.followerId, response.data);
          } catch (error) {
            console.error("获取用户信息失败:", error);
          }
        }
        // 获取被关注者信息
        if (item.followedId && !this.userInfoCache.has(item.followedId)) {
          try {
            const response = await getUser(item.followedId);
            this.userInfoCache.set(item.followedId, response.data);
          } catch (error) {
            console.error("获取用户信息失败:", error);
          }
        }
      }
      // 强制更新视图
      this.$forceUpdate();
    },
    /** 标签页点击事件 */
    handleTabClick(tab) {
      if (tab.name === "following") {
        this.getFollowingList();
      } else if (tab.name === "followers") {
        this.getFollowersList();
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.followingQueryParams.pageNum = 1;
      this.followersQueryParams.pageNum = 1;
      if (this.activeTab === "following") {
        this.getFollowingList();
      } else {
        this.getFollowersList();
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 添加关注按钮操作 */
    handleFollow() {
      this.followOpen = true;
      this.followTitle = "添加关注";
      this.followForm = {
        followerId: undefined,
        followedId: undefined
      };
    },
    /** 提交关注表单 */
    submitFollowForm() {
      this.$refs["followForm"].validate(valid => {
        if (valid) {
          follow(this.followForm.followerId, this.followForm.followedId).then(response => {
            this.$modal.msgSuccess("关注成功");
            this.followOpen = false;
            this.handleQuery();
          });
        }
      });
    },
    /** 取消关注 */
    handleUnfollow(row) {
      this.$modal.confirm('是否确认取消对该用户的关注？').then(function() {
        return unfollow(row.followerId, row.followedId);
      }).then(() => {
        this.handleQuery();
        this.$modal.msgSuccess("取消关注成功");
      }).catch(() => {});
    },
    /** 取消按钮 */
    cancelFollow() {
      this.followOpen = false;
      this.resetFollowForm();
    },
    /** 表单重置 */
    resetFollowForm() {
      this.followForm = {
        followerId: undefined,
        followedId: undefined
      };
      this.resetForm("followForm");
    },
    /** 查看用户 */
    handleViewUser(userId) {
      // 跳转到用户详情页面
      this.$router.push("/system/user/info/" + userId);
    },
    /** 关注列表多选框选中数据 */
    handleFollowingSelectionChange(selection) {
      // 处理多选逻辑
    },
    /** 粉丝列表多选框选中数据 */
    handleFollowersSelectionChange(selection) {
      // 处理多选逻辑
    },
    /** 获取用户昵称 */
    getUserNickName(userId) {
      const userInfo = this.userInfoCache.get(userId);
      return userInfo ? userInfo.nickName || userInfo.userName || userId : userId;
    }
  }
};
</script>